package com.vhome.idea;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.vhome.idea.entity.WechatDocument;

public class SogouWechatOpenIdFeeder {

	private static String PAGE_TAG = "page";
	private static String ITEMS_TAG = "items";
	private static String TOTALITEMS_TAG = "totalItems";
	private static String TOTALPAGES_TAG = "totalPages";

	public String feedWechatOpenId(String openId, int page) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpget = new HttpGet(
				"http://weixin.sogou.com/gzhjs?cb=sogou.weixin.gzhcb&openid="
						+ openId + "&page=" + page);
		System.out.println("executing request " + httpget.getURI());
		CloseableHttpResponse response = httpclient.execute(httpget);
		
		String rss;
		try {
			HttpEntity entity = response.getEntity();
			String content = EntityUtils.toString(entity);
			rss = parseSogouWechatEntity(content);
			EntityUtils.consume(entity);
		} finally {
			response.close();
		}
		return rss;
	}

	private String parseSogouWechatEntity(String content) {
		int startIndex = content.indexOf('(');
		int endIndex = content.lastIndexOf(')');
		String jsonContent = content.substring(startIndex + 1, endIndex);
		JSONObject object = new JSONObject(jsonContent);
		int page = (int) object.get(PAGE_TAG);
		JSONArray items = (JSONArray) object.get(ITEMS_TAG);
		int totalItems = (int) object.get(TOTALITEMS_TAG);
		int totalPages = (int) object.get(TOTALPAGES_TAG);
		System.out.println("page: " + page);
		System.out.println("totalItems: " + totalItems);
		System.out.println("totalPages: " + totalPages);

		List<WechatDocument> documentList = new ArrayList<>();
		for (int i = 0; i != items.length(); i++) {
			documentList.add(parseWechatDocumentXML(items.get(i).toString()));
		}
		
		return SogouWechatRSSGenerator.generateRSS(documentList);
	}

	private WechatDocument parseWechatDocumentXML(String xml) {
		WechatDocument document = new WechatDocument();
		XStream xstream = new XStream(new DomDriver());
		xstream.processAnnotations(WechatDocument.class);
		document = (WechatDocument) xstream.fromXML(xml);
		return document;
	}
}
